/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/sort-comp */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Select, DatePicker, Modal, message, Progress } from 'antd';
import moment from 'moment';
import { debounce } from 'lodash';
import StandardTable from '@/components/StandardTable';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import InfoCheck from '@/components/InfoCheck';
import Exception from '@/components/Exception';
import styles from './style.less';
import UploadWithCrypto from '@/components/upload-width-crypto';

const { Option } = Select;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { confirm } = Modal;

@connect(({ loading, fastMsg, setting }) => ({
  fastMsg,
  userType: setting.options.key,
  loading: loading.effects['fastMsg/getList'],
  specialAdd: loading.effects['fastMsg/specialAdd'],
  specialDel: loading.effects['fastMsg/specialDel'],
}))
@Form.create()
class FastMsg extends PureComponent {
  handleStandardTableChange = debounce(
    pagination => {
      const params = {
        page: pagination.current,
      };
      this.getList(params);
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor() {
    super();
    this.state = {
      selectedRows: [],
      visible: false,
      searchData: {
        start_date: moment()
          .startOf('day')
          .subtract(7, 'days'),
        end_date: moment().endOf('day'),
      },
      isShowProgress: false,
      hasGpAuthroty: true,
    };
    this.status = [
      {
        key: '*',
        label: '全部类型',
      },
      {
        key: '1',
        label: '拦截件',
      },
      {
        key: '2',
        label: '到付件',
      },
      {
        key: '3',
        label: '代收货款件',
      },
    ];
    this.columns = [
      {
        title: '单号',
        dataIndex: 'waybill_no',
        key: 'waybill_no',
      },
      {
        title: '快件类型',
        dataIndex: 'type_str',
        key: 'type_str',
      },
      {
        title: '快件金额(元)',
        dataIndex: 'amount',
        key: 'amount',
      },
      {
        title: '录入时间',
        dataIndex: 'create_at',
        key: 'create_at',
      },
    ];
    this.excel = {
      name: 'waybills',
      action: '/Api/Waybill/specialAdd',
      headers: {
        authorization: 'authorization-text',
      },
      data: {
        data_type: 'file',
      },
      showUploadList: false,
    };
  }

  uploadChange = info => {
    this.setState({
      isShowProgress: true,
    });
    if (info.file.status == 'uploading') {
      const { event } = info;
      if (event) {
        const percent = Math.floor((event.loaded / event.total) * 100);
        this.setState({
          percent,
        });
      }
    }
    if (info.file.status === 'done') {
      const { code, msg } = info.file.response;
      this.setState({
        percent: 0,
        isShowProgress: false,
      });
      if (code == 0) {
        message.success(msg);
        this.getList();
      } else {
        this.showWarning(msg);
      }
    }
  };

  showWarning = msg => {
    Modal.warning({
      title: '温馨提示',
      centered: true,
      okText: '确定',
      content: msg,
    });
  };

  okChange = () => {
    const { form, dispatch } = this.props;
    const { validateFields } = form;
    validateFields((err, fieldsValue) => {
      localStorage.setItem('fastType', fieldsValue.type);
      fieldsValue.waybills = fieldsValue.waybills.replace(/\n/g, ',').replace(/\s+/g, '  ');
      dispatch({
        type: 'fastMsg/specialAdd',
        payload: {
          ...fieldsValue,
          ...{
            data_type: 'text',
          },
        },
        then: res => {
          const { code, msg } = res;
          if (code == 0) {
            message.success(msg);
            dispatch({
              type: 'fastMsg/save',
              payload: {
                visible: false,
              },
            });
            this.getList();
          } else {
            this.showWarning(msg);
          }
        },
      });
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  showConfirm = params => {
    confirm({
      centered: true,
      okText: '确定',
      cancelText: '取消',
      title: '温馨提示',
      ...params,
    });
  };

  // 批量删除
  handleBatchDelete = data => {
    const { dispatch } = this.props;
    let ids = [];
    data.forEach(v => {
      ids.push(v.id);
    });
    ids = ids.join(',');
    if (data == '') {
      message.error('请至少选择一项');
      return;
    }
    this.showConfirm({
      okText: '是',
      cancelText: '否',
      content: '是否删除快件',
      onOk: () => {
        dispatch({
          type: 'fastMsg/specialDel',
          payload: {
            ids,
          },
          then: res => {
            if (res.code == 0) {
              this.getList();
            }
          },
        });
      },
    });
  };

  // 查询表单
  searchForm = () => {
    const SearchForm = Form.create()(props => {
      const { form } = props;
      const { dispatch } = this.props;
      const { getFieldDecorator } = form;
      this.getFieldsValue = () => {
        const values = form.getFieldsValue();
        const { date } = values;
        if (date) {
          values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
          const [start, end] = values.date;
          values.start_date = start;
          values.end_date = end;
          delete values.date;
          values.type = values.type == '*' ? '' : values.type;
        }
        return values;
      };
      this.getList = params => {
        const values = this.getFieldsValue();
        this.setState({
          // 防止表单清空
          searchData: {
            ...values,
            ...{
              start_date: form.getFieldsValue().date[0],
              end_date: form.getFieldsValue().date[1],
            },
          },
        });
        dispatch({
          type: 'fastMsg/getList',
          payload: {
            ...values,
            ...params,
          },
        });
      };
      this.downloadData = () => {
        const values = this.getFieldsValue();
        const data = {
          download: 1,
          ...values,
        };
        this.getList(data);
      };
      const handleSearch = debounce(
        e => {
          e.preventDefault();
          this.getList();
        },
        500,
        {
          leading: true,
          trailing: false,
        },
      );
      const { start_date, end_date, waybill, type } = this.state.searchData;
      return (
        <Form onSubmit={handleSearch} layout="inline">
          <FormItem className={styles.w200}>
            {getFieldDecorator('date', {
              initialValue: [start_date, end_date],
            })(<RangePicker placeholder={['开始日期', '结束日期']} />)}
          </FormItem>
          <FormItem>
            {getFieldDecorator('type', {
              initialValue: type || '*',
            })(
              <Select style={{ width: 110 }}>
                {this.status.map(item => (
                  <Option key={item.key}>{item.label}</Option>
                ))}
              </Select>,
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('waybill', {
              initialValue: waybill || '',
            })(<Input style={{ width: 200 }} maxLength={20} placeholder="请输入运单编号" />)}
          </FormItem>
          <FormItem>
            <Button type="primary" htmlType="submit" icon="search">
              查询
            </Button>
          </FormItem>
          <FormItem style={{ margin: '0' }}>
            <Button type="primary" icon="download" onClick={this.downloadData}>
              导出
            </Button>
            {/* <DownloadBar href="/Api/Waybill/specialList" query={this.downloadData}>
            </DownloadBar> */}
          </FormItem>
        </Form>
      );
    });
    return <SearchForm />;
  };

  handleInfoReady(data) {
    const { dispatch } = this.props;
    if (!data.name) return;
    dispatch({
      type: 'allocation/getUserInfo',
    }).then(res => {
      const { data: { is_gp } = {} } = res;
      this.setState({
        hasGpAuthroty: is_gp == '1',
      });
    });
    this.getList();
  }

  handleSelectRow(selectedRows) {
    this.setState({
      selectedRows,
    });
  }

  render() {
    const { form, fastMsg, dispatch, loading, userType } = this.props;
    const { selectedRows, hasGpAuthroty } = this.state;
    const { getFieldDecorator } = form;
    const { list, pagination, visible } = fastMsg;
    const data = { list, pagination };
    if (!hasGpAuthroty && userType == 'post') {
      // 当县级网点无共配权限时，提示无权限
      return <Exception type="403" title="您所在的网点尚未开通共配服务，请联系中邮总公司开通！" />;
    }
    return (
      <PageHeaderLayout title="快件信息下发">
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
        <div className={styles.main}>
          <div className={styles.header}>
            <div style={{ marginTop: '4px' }}>
              <Button
                type="primary"
                className={styles.mr10}
                onClick={() => dispatch({ type: 'fastMsg/save', payload: { visible: true } })}
              >
                快件录入
              </Button>
              <UploadWithCrypto {...this.excel} className={styles.mr10} onChange={this.uploadChange}>
                <Button type="primary">Excel导入</Button>
              </UploadWithCrypto>
              <Button
                icon="question-circle"
                href="//m.kuaidihelp.com/help/importHelp"
                target="_blank"
              >
                导入帮助
              </Button>
            </div>
            {this.searchForm()}
          </div>
          <StandardTable
            rowKey="id"
            loading={loading}
            selectedRows={selectedRows}
            onSelectRow={this.handleSelectRows}
            data={data}
            columns={this.columns}
            onChange={this.handleStandardTableChange}
          />
        </div>
        <Modal
          destroyOnClose
          title="快件录入"
          visible={visible}
          width="800px"
          centered
          onCancel={() => dispatch({ type: 'fastMsg/save', payload: { visible: false } })}
          onOk={this.okChange}
        >
          <Form>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="快递单号">
              {form.getFieldDecorator('waybills', {
                rules: [{ required: true, message: '请输入快递单号!' }],
              })(
                <TextArea
                  style={{ height: '300px', resize: 'none' }}
                  placeholder="请输入多个单号，输入多个单号请换行，如需输入快件金额，请在对应单号后面空两格输入金额，如78521552589655  32"
                />,
              )}
            </FormItem>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="快件类型">
              {getFieldDecorator('type', {
                initialValue: localStorage.getItem('fastType')
                  ? localStorage.getItem('fastType')
                  : '1',
              })(
                <Select style={{ width: 110 }}>
                  {this.status.map(
                    (item, index) => index > 0 && <Option key={item.key}>{item.label}</Option>,
                  )}
                </Select>,
              )}
            </FormItem>
          </Form>
        </Modal>
        <div style={{ padding: '10px 30px' }}>
          <a onClick={() => this.handleBatchDelete(selectedRows)}>批量删除</a>
        </div>
        <Modal
          visible={this.state.isShowProgress}
          footer={null}
          width="120px"
          closable={false}
          centered
          wrapClassName="progress"
        >
          <Progress type="circle" percent={this.state.percent} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}

export default FastMsg;
